package crm8000.services

import crm8000.Models.GoodsUnit;
import crm8000.helper.Result;
import grails.transaction.Transactional

@Transactional
class GoodsService {

	def IdGenService idGenService

	def allUnits() {
		return GoodsUnit.listOrderByName()
	}

	Result editUnit(params) {
		if (params.unitId) {
			// 编辑
			def u = GoodsUnit.countByNameAndUnitIdNotEqual(params.name, params.unitId)
			if (u > 0) {
				return new Result(success: false, msg: "商品计量单位 [${params.name}] 已经存在")
			}

			def unit = GoodsUnit.findByUnitId(params.unitId)
			unit.name = params.name

			unit.save()
			return new Result(success: true, id: unit.unitId)
		} else {
			// 新增
			def u = GoodsUnit.countByName(params.name)
			if (u > 0) {
				return new Result(success: false, msg: "商品计量单位 [${params.name}] 已经存在")
			}

			def unit = new GoodsUnit()
			unit.unitId = idGenService.newId()
			unit.name = params.name

			unit.save()
			return new Result(success: true, id: unit.unitId)
		}
	}

	Result deleteUnit(String unitId) {
		def unit = GoodsUnit.findByUnitId(unitId)
		unit?.delete()

		return new Result(success: true)
	}
}
